import { useAxiosWebGet, useAxiosWebPost, useModal, useModel } from "@sker/sdk";
import { renderAdminPage, Deving, UserSelector, SysRoleSelector, useServerData, MenuSelector } from "@sker/ui";
import { SysUser } from "@sker/model";
import { App, Button, Empty, Modal, Tabs } from "antd";
import { Card } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { ActionType, BetaSchemaForm, PageContainer, ProTable } from "@ant-design/pro-components";
import { useEffect, useRef, useState } from "react";
import { useTabs } from '@sker/sdk'
export const RolePage: React.FC<{}> = () => {
    const [currentRole, setCurrentRole] = useState<object>();
    const [serverData] = useServerData();
    const { activeKey, props: tabsProps } = useTabs([{
        label: '菜单权限',
        key: 'menu-permission'
    }, {
        label: '包含用户',
        key: 'user'
    }], 'menu-permission');
    return <PageContainer title={serverData?.title || '角色管理'}>
        <div className="flex flex-col">
            <div className="flex">
                <div className="w-450px">
                    <SysRoleSelector multi={false} onSelect={record => setCurrentRole(record)} />
                </div>
                <div className="flex-1 ml-24px">
                    <Tabs className="bg-white px-24px empty rounded-8px" {...tabsProps}></Tabs>
                    <div className="mt-24px">
                        {activeKey === 'menu-permission' && <RoleMenuPermissionList role={currentRole} />}
                        {activeKey === 'api-permission' && <Deving />}
                        {activeKey === 'data-permission' && <Deving />}
                        {activeKey === 'user' && <RoleUserList role={currentRole} />}
                    </div>
                </div>
            </div>
        </div>
    </PageContainer>
}

renderAdminPage(RolePage, 'imeepos/core/web/role')

export const RoleUserList: React.FC<{ role: any }> = ({ role }) => {
    const { fetch: getCasbinRole, loading: getCasbinRoleLoading } = useAxiosWebGet('imeepos/core/casbin/role')
    const { fetch: postCasbinRole, loading: postCasbinRoleLoading } = useAxiosWebPost('imeepos/core/casbin/role', {})
    const { fetch: postCasbinRoleDel, loading: postCasbinRoleDelLoading } = useAxiosWebPost('imeepos/core/casbin/role/delRoleUser', {})
    const { props: modalProps, setOpen } = useModal(`${role?.title}-添加用户`)
    const [unames, setUnames] = useState<string[]>([])
    const { props: realnameModalProps, setOpen: setRealnameModalOpen, extra } = useModal('完善姓名')
    const sysUser = useModel(SysUser)
    const ref = useRef<ActionType>()
    if (!role) return <Empty description={'请选择角色'} />
    return <>
        <Modal {...realnameModalProps}>
            <BetaSchemaForm onFinish={async (values) => {
                if (!extra.uid) return App.useApp().message.error(`参数错误`)
                await sysUser.update(values, extra.uid, ['uid'])
                setRealnameModalOpen(false, null)
                ref.current?.reload();
            }} columns={[
                { title: '姓名', dataIndex: 'realname' }
            ]} />
        </Modal>
        <Modal {...modalProps} width={'1200px'}>
            <UserSelector value={unames} multi={true} onSelect={(unames: string[]) => {
                postCasbinRole({
                    name: role.id,
                    unames
                })
            }} />
        </Modal>
        <Card title={`${role.title}-用户管理`} extra={<Button type={'primary'} size="small" icon={<PlusOutlined />} onClick={() => setOpen(true)}></Button>}>
            <ProTable
                search={false}
                loading={getCasbinRoleLoading || postCasbinRoleLoading || postCasbinRoleDelLoading}
                toolBarRender={false}
                actionRef={ref}
                params={{
                    postCasbinRoleLoading,
                    postCasbinRoleDelLoading,
                    role
                }}
                rowKey={record => record.username}
                columns={[
                    { title: '用户名', dataIndex: 'username' },
                    {
                        title: '姓名',
                        dataIndex: 'realname',
                        render(dom, entity, index, action, schema) {
                            return <Button type={'link'} onClick={e => {
                                setRealnameModalOpen(true, { uid: entity.uid })
                            }}>{dom}</Button>
                        },
                    },
                    {
                        title: '操作',
                        render(dom, entity, index, action, schema) {
                            return <>
                                <Button danger size={'small'} type={'link'} onClick={() => {
                                    postCasbinRoleDel({ name: role.id, uname: entity.username })
                                }}>移除</Button>
                            </>
                        },
                    }
                ]}
                request={async () => {
                    return getCasbinRole({
                        name: role.id
                    }).then(res => {
                        setUnames(res.unames)
                        return res;
                    })
                }}
            />
        </Card>
    </>
}

export const RoleMenuPermissionList: React.FC<{ role: any }> = ({ role }) => {
    const { fetch: addCasbinMenu } = useAxiosWebPost('imeepos/core/casbin/menu')
    const { data, fetch: getCasbinMenu } = useAxiosWebGet('imeepos/core/casbin/menu')
    const handleKeys = (keys: string[]) => {

    }
    useEffect(() => {
        if (!role) return;
        getCasbinMenu({ role: role.id })
    }, [role])
    if (!role) return <Empty description={'请选择角色'} />
    return <>
        <Card title={`${role.title}-角色权限管理`}>
            <MenuSelector value={data} onSelect={(key, selected) => {
                addCasbinMenu({
                    role: role.id,
                    policy: key,
                    selected
                })
            }} />
        </Card>
    </>
}

